//
//  YBUserAuthVC.m
//  WuyouTang
//
//  Created by YB007 on 2020/8/28.
//  Copyright © 2020 cat. All rights reserved.
//

#import "YBUserAuthVC.h"

#import "YBStorageObj.h"

typedef NS_ENUM(NSInteger,CerType) {
    CerTypeDefault,
    CerTypeFace,
    CerTypeBack,
    CerTypeHand,
};

@interface YBUserAuthVC ()<TZImagePickerControllerDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate>
{
    NSString *_cerFacePath;
    NSString *_cerBackPath;
    NSString *_cerHandPath;
    BOOL _selectedImg;
}
@property(nonatomic,strong)MyTextField *nameTF;
@property(nonatomic,strong)MyTextField *cardTF;
@property(nonatomic,strong)MyTextField *phoneTF;

@property(nonatomic,strong)UIButton *cerFaceBtn;
@property(nonatomic,strong)UIImage *cerFaceImg;
@property(nonatomic,strong)UIButton *cerBackBtn;
@property(nonatomic,strong)UIImage *cerBackImg;
@property(nonatomic,strong)UIButton *cerHandBtn;
@property(nonatomic,strong)UIImage *cerHandImg;

@property(nonatomic,assign)CerType upCerType;

@property(nonatomic,strong)UIButton *stateBtn;
@end

@implementation YBUserAuthVC

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    if (_upCerType == CerTypeDefault) {
        [self pullData];
    }
}


-(void)pullData {
    YBWeakSelf;
    [WYNetworking postWithUrl:@"Auth.getAuth" Dic:@{} Suc:^(int code, id info, NSString *msg) {
        if (code == 0) {
            [weakSelf updateData:[info firstObject]];
        }else {
            [MBProgressHUD showPop:msg];
            [weakSelf.navigationController popViewControllerAnimated:YES];
        }
    } Fail:^(id fail) {
            
    }];
}
-(void)updateData:(NSDictionary *)infoDic {
    int state = [minstr([infoDic valueForKey:@"status"]) intValue];
    //-1未认证过 0审核中 1通过 2拒绝
    switch (state) {
        case 0:{
            [self changeStateBtnEnable:NO];
            [_stateBtn setTitle:YZMsg(@"信息审核中") forState:0];
        }break;
        case 1:{
            [self changeStateBtnEnable:NO];
            [_stateBtn setTitle:YZMsg(@"审核已通过") forState:0];
        }break;
        case 2:{
            [self changeStateBtnEnable:YES];
            [_stateBtn setTitle:YZMsg(@"审核被拒,提交重审") forState:0];
        }break;
        default:{
            [self changeStateBtnEnable:YES];
            [_stateBtn setTitle:YZMsg(@"开始认证") forState:0];
        }break;
    }
    _nameTF.text = [PublicObj checkNull:minstr([infoDic valueForKey:@"real_name"])] ? @"":minstr([infoDic valueForKey:@"real_name"]);
    _cardTF.text = [PublicObj checkNull:minstr([infoDic valueForKey:@"cer_no"])] ? @"":minstr([infoDic valueForKey:@"cer_no"]);
    _phoneTF.text = [PublicObj checkNull:minstr([infoDic valueForKey:@"mobile"])] ? @"":minstr([infoDic valueForKey:@"mobile"]);
    
    _cerFacePath = minstr([infoDic valueForKey:@"front_view"]);
    if (![PublicObj checkNull:_cerFacePath]) {
        [_cerFaceBtn sd_setImageWithURL:[NSURL URLWithString:_cerFacePath] forState:0];
    }
    _cerBackPath = minstr([infoDic valueForKey:@"back_view"]);
    if (![PublicObj checkNull:_cerBackPath]) {
        [_cerBackBtn sd_setImageWithURL:[NSURL URLWithString:_cerBackPath] forState:0];
    }
    _cerHandPath = minstr([infoDic valueForKey:@"handset_view"]);
    if (![PublicObj checkNull:_cerHandPath]) {
        [_cerHandBtn sd_setImageWithURL:[NSURL URLWithString:_cerHandPath] forState:0];
    }
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.titleL.text = YZMsg(@"实名认证");
    
    NSArray *defaultArray = @[@{@"title":YZMsg(@"真实姓名"),@"placeholder":YZMsg(@"请输入姓名")},
                              @{@"title":YZMsg(@"身份证号"),@"placeholder":YZMsg(@"请输入身份证号码")},
                              @{@"title":YZMsg(@"手机号码"),@"placeholder":YZMsg(@"请输入手机号码")}];
    
    MASViewAttribute *masTop = self.naviView.mas_bottom;
    
    for (int i=0; i<defaultArray.count; i++) {
        NSDictionary *subDic = defaultArray[i];
        UILabel *titleL = [[UILabel alloc]init];
        titleL.font = SYS_Font(15);
        titleL.textColor = RGB_COLOR(@"#dcdcdc", 1);
        titleL.text = minstr([subDic valueForKey:@"title"]);
        [self.view addSubview:titleL];
        [titleL mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self.view.mas_left).offset(15);
            make.top.equalTo(masTop).offset(18);
            make.width.mas_equalTo(80);
        }];
        
        MyTextField *tf = [[MyTextField alloc]init];
        tf.placeCol = RGB_COLOR(@"#646464", 1);
        tf.textColor = RGB_COLOR(@"#dcdcdc", 1);
        tf.tintColor = RGB_COLOR(@"#dcdcdc", 1);
        tf.placeholder = minstr([subDic valueForKey:@"placeholder"]);
        tf.font = SYS_Font(15);
        [self.view addSubview:tf];
        switch (i) {
            case 0:{
                _nameTF = tf;
            }break;
            case 1:{
                _cardTF = tf;
            }break;
            case 2:{
                _phoneTF = tf;
                _phoneTF.keyboardType = UIKeyboardTypeNumberPad;
            }break;
            default:
                break;
        }
        [tf mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(titleL.mas_right).offset(5);
            make.right.equalTo(self.view.mas_right).offset(-15);
            make.height.mas_equalTo(32);
            make.centerY.equalTo(titleL);
        }];
        UILabel *lineL = [[UILabel alloc]init];
        lineL.backgroundColor = Line_Cor;
        [self.view addSubview:lineL];
        [lineL mas_makeConstraints:^(MASConstraintMaker *make) {
            make.width.equalTo(self.view.mas_width).offset(-30);
            make.centerX.equalTo(self.view);
            make.height.mas_equalTo(1);
            make.top.equalTo(titleL.mas_bottom).offset(18);
        }];
        masTop = lineL.mas_bottom;
    }
    
    NSArray *certificatesA = @[YZMsg(@"证件正面"),YZMsg(@"证件反面"),YZMsg(@"手持证件正面照")];
    CGFloat space = 20;
    CGFloat cerW = (_window_width - 20*4)/3;
    CGFloat cerH = cerW *75/100;
    MASViewAttribute *cerLeft = self.view.mas_left;
    MASViewAttribute *cerTop = masTop;
    for (int i =0; i<certificatesA.count; i++) {
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        btn.layer.cornerRadius = 3;
        btn.layer.masksToBounds = YES;
        [btn setImage:[UIImage imageNamed:@"认证-上传"] forState:0];
        btn.imageView.contentMode = UIViewContentModeScaleAspectFill;
        btn.contentVerticalAlignment = UIControlContentVerticalAlignmentFill;
        btn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentFill;
        [btn addTarget:self action:@selector(clickCerBtn:) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:btn];
        switch (i) {
            case 0:{
                _cerFaceBtn = btn;
            }break;
            case 1:{
                _cerBackBtn = btn;
            }break;
            case 2:{
                _cerHandBtn = btn;
            }break;
            default:
                break;
        }
        [btn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(cerLeft).offset(space);
            make.top.equalTo(cerTop).offset(18);
            make.width.mas_equalTo(cerW);
            make.height.mas_equalTo(cerH);
        }];
        UILabel *desL = [[UILabel alloc]init];
        desL.font = SYS_Font(12);
        desL.textColor = RGB_COLOR(@"@646464", 1);
        desL.text = certificatesA[i];
        [self.view addSubview:desL];
        [desL mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(btn);
            make.width.lessThanOrEqualTo(btn.mas_width).offset(20);
            make.top.equalTo(btn.mas_bottom).offset(10);
        }];
        cerLeft = btn.mas_right;
        masTop = desL.mas_bottom;
    }
    
    UIImageView *desIV = [[UIImageView alloc]init];
    desIV.image = [UIImage imageNamed:@"认证-示例"];
    desIV.layer.cornerRadius = 3;
    desIV.layer.masksToBounds = YES;
    [self.view addSubview:desIV];
    [desIV mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view.mas_left).offset(20);
        make.top.equalTo(masTop).offset(26);
        make.width.mas_equalTo(cerW);
        make.height.mas_equalTo(cerH);
    }];
    UILabel *cerDesL = [[UILabel alloc]init];
    cerDesL.font = SYS_Font(12);
    cerDesL.text = YZMsg(@"请按图示手持证件拍照，必须本人手持身份证，确保证件信息清晰可见。");
    cerDesL.textColor = RGB_COLOR(@"#646464", 1);
    cerDesL.numberOfLines = 0;
    [self.view addSubview:cerDesL];
    [cerDesL mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(desIV.mas_right).offset(12);
        make.top.equalTo(desIV.mas_top);
        make.right.lessThanOrEqualTo(self.view.mas_right).offset(-20);
    }];
    
    _stateBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [_stateBtn setTitleColor:RGB_COLOR(@"#ffffff", 1) forState:0];
    [_stateBtn addTarget:self action:@selector(clickStateBtn) forControlEvents:UIControlEventTouchUpInside];
    _stateBtn.titleLabel.font = SYS_Font(15);
    _stateBtn.layer.cornerRadius = 3;
    _stateBtn.layer.masksToBounds = YES;
    [_stateBtn setTitle:YZMsg(@"开始认证") forState:0];
    [self.view addSubview:_stateBtn];
    [_stateBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.equalTo(self.view.mas_width).offset(-40);
        make.centerX.equalTo(self.view);
        make.height.mas_equalTo(40);
        make.top.equalTo(desIV.mas_bottom).offset(40);
    }];
    [self changeStateBtnEnable:YES];
    
}
-(void)changeStateBtnEnable:(BOOL)enable {
    
    _nameTF.userInteractionEnabled = enable;
    _cardTF.userInteractionEnabled = enable;
    _phoneTF.userInteractionEnabled = enable;
    _cerFaceBtn.userInteractionEnabled = enable;
    _cerBackBtn.userInteractionEnabled = enable;
    _cerHandBtn.userInteractionEnabled = enable;
    
    _stateBtn.enabled = enable;
    if (enable) {
        _stateBtn.backgroundColor = Pink_Cor;
    }else{
        _stateBtn.backgroundColor = RGB_COLOR(@"#ffffff", 0.21);
    }
}


-(void)clickCerBtn:(UIButton *)sender {
    [self.view endEditing:YES];
    
    if (sender == _cerFaceBtn) {
        _upCerType = CerTypeFace;
    }else if (sender == _cerBackBtn){
        _upCerType = CerTypeBack;
    }else{
        _upCerType = CerTypeHand;
    }
    
    YBWeakSelf;
    RKActionSheet *sheet = [[RKActionSheet alloc]initWithTitle:@""];
    [sheet addActionWithType:RKSheet_Default andTitle:YZMsg(@"相机") complete:^{
        [weakSelf takePhoto];
    }];
    [sheet addActionWithType:RKSheet_Default andTitle:YZMsg(@"相册") complete:^{
        [weakSelf selectPhotos];
    }];
    [sheet addActionWithType:RKSheet_Cancle andTitle:YZMsg(@"取消") complete:^{
    }];
    [sheet showSheet];
    
}
-(void)clickStateBtn {
    [self.view endEditing:YES];
   
    if (_nameTF.text.length <=0 ) {
        [MBProgressHUD showPop:YZMsg(@"请输入姓名")];
        return;
    }
    if (_cardTF.text.length <=0 ) {
        [MBProgressHUD showPop:YZMsg(@"请输入身份证号码")];
        return;
    }
    if (_phoneTF.text.length <=0 ) {
        [MBProgressHUD showPop:YZMsg(@"请输入手机号码")];
        return;
    }
    if ((!_cerFaceImg && [PublicObj checkNull:_cerFacePath]) ||
        (!_cerBackImg && [PublicObj checkNull:_cerBackPath]) ||
        (!_cerHandImg && [PublicObj checkNull:_cerHandPath])) {
        [MBProgressHUD showPop:YZMsg(@"请完善证件信息")];
        return;
    }
    
    if (_selectedImg) {
        //进行上传操作
        YBWeakSelf;
        [[YBStorageObj storageManeger]getCOSType:^(int code) {
            dispatch_async(dispatch_get_main_queue(), ^{
                if (code == 0) {
                    [weakSelf startUploadCer];
                }
            });
        }];
    }else{
        //未更改图片直接请求
        [MBProgressHUD showMessage:@""];
        [self goResServer];
    }
    
    
}
-(void)startUploadCer {
    [MBProgressHUD showMessage:@""];
    dispatch_group_t group = dispatch_group_create();
    dispatch_queue_t queue = dispatch_get_global_queue(0, 0);
    dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
    YBWeakSelf;
    //正面照
    if (_cerFaceImg) {
        dispatch_group_async(group, queue, ^{
            NSString *imageName = [PublicObj getNameBaseCurrentTime:@"_cerFace.png"];
            [[YBStorageObj storageManeger]yb_storageImg:_cerFaceImg andName:imageName progress:^(CGFloat percent) {
                
            }complete:^(int code, NSString *key) {
                _cerFacePath = minstr(key);
                dispatch_semaphore_signal(semaphore);
            }];
            dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
        });
    }
    
    //反面照
    if (_cerBackImg) {
        dispatch_group_async(group, queue, ^{
            NSString *imageName = [PublicObj getNameBaseCurrentTime:@"_cerBack.png"];
            [[YBStorageObj storageManeger]yb_storageImg:_cerBackImg andName:imageName progress:^(CGFloat percent) {
                
            }complete:^(int code, NSString *key) {
                _cerBackPath = minstr(key);
                dispatch_semaphore_signal(semaphore);
            }];
            dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
        });
    }
    
    //手持照
    if (_cerHandImg) {
        dispatch_group_async(group, queue, ^{
            NSString *imageName = [PublicObj getNameBaseCurrentTime:@"_cerHand.png"];
            [[YBStorageObj storageManeger]yb_storageImg:_cerHandImg andName:imageName progress:^(CGFloat percent) {
                
            }complete:^(int code, NSString *key) {
                _cerHandPath = minstr(key);
                dispatch_semaphore_signal(semaphore);
            }];
            dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
        });
    }
    dispatch_group_notify(group, queue, ^{
        dispatch_async(dispatch_get_main_queue(), ^{
            [weakSelf goResServer];
        });
        NSLog(@"任务完成执行");
    });
}
-(void)goResServer {

    NSDictionary *postDic = @{@"real_name":_nameTF.text,
                              @"mobile":_phoneTF.text,
                              @"cer_no":_cardTF.text,
                              @"front_view":_cerFacePath?_cerFacePath:@"",
                              @"back_view":_cerBackPath?_cerBackPath:@"",
                              @"handset_view":_cerHandPath?_cerHandPath:@"",
    };
    
    YBWeakSelf;
    [WYNetworking postWithUrl:@"Auth.setAuth" Dic:postDic Suc:^(int code, id info, NSString *msg) {
        [MBProgressHUD hideHUD];
        [MBProgressHUD showPop:msg];
        if (code == 0) {
            [weakSelf.navigationController popViewControllerAnimated:YES];
        }
    } Fail:^(id fail) {
        [MBProgressHUD hideHUD];
    }];
    
}

- (void)takePhoto{
    // 区分拍照-相册
    UIImagePickerController *imagePickerController = [UIImagePickerController new];
    imagePickerController.delegate = self;
    imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
    imagePickerController.allowsEditing = NO;
    imagePickerController.showsCameraControls = YES;
    imagePickerController.cameraDevice = UIImagePickerControllerCameraDeviceRear;
    [self presentViewController:imagePickerController animated:YES completion:nil];
}
-(void)selectPhotos {
    TZImagePickerController *imagePC = [[TZImagePickerController alloc]initWithMaxImagesCount:1 delegate:self];
    imagePC.preferredLanguage = [lagType isEqual:ZH_CN] ? @"zh-Hans":@"en";
    imagePC.showSelectBtn = YES;
    imagePC.allowCrop = NO;
    imagePC.allowPickingOriginalPhoto = NO;
    imagePC.oKButtonTitleColorNormal = Pink_Cor;
    imagePC.allowTakePicture = YES;
    imagePC.allowTakeVideo = NO;
    imagePC.allowPickingVideo = NO;
    imagePC.allowPickingMultipleVideo = NO;
    imagePC.modalPresentationStyle = 0;
    [[[YBBaseAppDelegate sharedAppDelegate] topViewController]presentViewController:imagePC animated:YES completion:nil];
}
- (void)imagePickerController:(TZImagePickerController *)picker didFinishPickingPhotos:(NSArray<UIImage *> *)photos sourceAssets:(NSArray *)assets isSelectOriginalPhoto:(BOOL)isSelectOriginalPhoto{
    _selectedImg = YES;
    [self changeUIWithImg:photos[0]];
}
-(void)changeUIWithImg:(UIImage *)image {
    switch (_upCerType) {
        case CerTypeFace:{
            _cerFaceImg = image;
            [_cerFaceBtn setImage:image forState:0];
        }break;
        case CerTypeBack:{
            _cerBackImg = image;
            [_cerBackBtn setImage:image forState:0];
        }break;
        case CerTypeHand:{
            _cerHandImg = image;
            [_cerHandBtn setImage:image forState:0];
        }break;
        default:
            break;
    }
}
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    NSString *type = [info objectForKey:UIImagePickerControllerMediaType];
    if ([type isEqualToString:@"public.image"]){
        _selectedImg = YES;
        //先把图片转成NSData
        UIImage* image = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
        [self changeUIWithImg:image];
    }
    [picker dismissViewControllerAnimated:YES completion:nil];
}
-(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    [picker dismissViewControllerAnimated:YES completion:nil];
}
- (void)navigationController:(UINavigationController *)navigationController didShowViewController:(UIViewController *)viewController animated:(BOOL)animated {
    if ([UIDevice currentDevice].systemVersion.floatValue < 11) {
        return;
    }
    if ([viewController isKindOfClass:NSClassFromString(@"PUPhotoPickerHostViewController")]) {
        [viewController.view.subviews enumerateObjectsUsingBlock:^(__kindof UIView * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            if (obj.frame.size.width < 42) {
                [viewController.view sendSubviewToBack:obj];
                *stop = YES;
            }
        }];
    }
}


@end
